/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("InventoryCount",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.demo.IServices;
using VOL.Entity.DomainModels;

namespace VOL.demo.Controllers
{
    [AllowAnonymous]
    public partial class InventoryCountController
    {
        private readonly IInventoryCountService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public InventoryCountController(
            IInventoryCountService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 分页查询盘点单列表
        /// 前端可以根据盘点单号、类型、仓库、状态和时间范围查询
        /// </summary>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="countCode">盘点单号，支持模糊</param>
        /// <param name="countType">盘点类型</param>
        /// <param name="warehouseId">仓库ID</param>
        /// <param name="countStatus">盘点状态（例如：有/无盈亏）</param>
        /// <param name="startTime">开始时间（包含）</param>
        /// <param name="endTime">结束时间（包含）</param>
        /// <param name="creatorId">制单人ID</param>
         
        
        [HttpGet("GetInventoryCountPageList")]
        public async Task<IActionResult> GetInventoryCountPageList(
            int pageIndex = 1,
            int pageSize = 10,
            string countCode = null,
            string countType = null,
            int? warehouseId = null,
            string countStatus = null,
            DateTime? startTime = null,
            DateTime? endTime = null,
            int? creatorId = null)
        {
            try
            {
                var result = await _service.GetInventoryCountPageListAsync(
                    pageIndex: pageIndex,
                    pageSize: pageSize,
                    countCode: countCode,
                    countType: countType,
                    warehouseId: warehouseId,
                    countStatus: countStatus,
                    startTime: startTime,
                    endTime: endTime,
                    creatorId: creatorId
                );
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据盘点单号获取该盘点的明细列表
        /// 用于编辑页/查看页加载明细
        /// </summary>
        /// <param name="countCode">盘点单号</param>
        [HttpGet("GetCountItems")]
        public async Task<IActionResult> GetCountItems(string countCode)
        {
            try
            {
                if (string.IsNullOrEmpty(countCode))
                    return BadRequest(new { success = false, message = "盘点单号不能为空" });

                var items = await _service.GetItemsByCountCodeAsync(countCode);
                return Ok(new { success = true, data = items, message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 保存盘点单（包含主表与明细）
        /// 业务说明：
        /// - 前端应先选择仓库并保存主信息（可由同一接口在没有明细时只保存主表）
        /// - 在已选择仓库后前端可新增明细（明细货品来自该仓库的库存），提交时将主表与明细一并发送到此接口保存
        /// - 服务端会在事务中保存主表与明细，并为每条明细计算盈亏数量与金额以及盘点状态（盘盈/盘亏/无盈亏）
        /// </summary>
        /// <param name="request">保存请求，包含 InventoryCount（主表） 和 CountItems（明细）</param>
        [HttpPost("SaveInventoryCount")]
        public async Task<IActionResult> SaveInventoryCount([FromBody] SaveInventoryCountRequest request)
        {
            try
            {
                var result = await _service.SaveInventoryCountAsync(request);
                if (result == null)
                    return BadRequest(new { success = false, message = "保存失败：未知错误" });

                if (result.Status)
                    return Ok(new { success = true, message = result.Message, data = result.Data });
                else
                    return BadRequest(new { success = false, message = result.Message });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"保存失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据盘点单主键删除盘点单（同时删除其明细）
        /// 注意：这是物理删除，前端请谨慎调用
        /// </summary>
        /// <param name="id">盘点单主键ID</param>
        [HttpDelete("Delete/{id}")]
        public IActionResult DeleteInventoryCount(int id)
        {
            try
            {
                if (id <= 0) return BadRequest(new { success = false, message = "无效的ID" });

                var res = _service.Del(new object[] { id }, true);
                if (res.Status)
                    return Ok(new { success = true, message = res.Message });
                return BadRequest(new { success = false, message = res.Message });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }
    }
}
